#
# plugins/SurveillanceCameras/__init__.py
#
# Copyright (C) 2013
# Walter Kraembring, Steve Castano
#
##############################################################################
# Revision history:
#
# 2013-05-23  The first stumbling version
# 2013-05-23  Added config options without needing to know the CGI code.
##############################################################################

eg.RegisterPlugin(
    name = "SurveillanceCameras",
    guid = '{D06E1E7D-9389-46DD-92AE-D9001118F121}',
    author = "Walter Kraembringm, Steve Castano",
    version = "0.0.2",
    canMultiLoad = False,
    kind = "external",
    url = "http://www.eventghost.org",
    description = (
        "A plugin used to define and configure surveillance cameras"+
        " for taking n numbers of snapshots when triggered"
    )
)

import datetime
import time
import os
import sys
import urllib2
from threading import Event, Thread
from datetime import datetime

class Text:
    started = "Plugin started"



class SurveillanceCameras(eg.PluginClass):
    text = Text
        
    def __init__(self):
        self.AddAction(TakeSnapShots)
        self.started = False


    def __start__(
        self
    ):
        print self.text.started


    def __stop__(self):
        self.started = False


    def __close__(self):
        self.started = False



class TakeSnapShots(eg.ActionClass):

    class text:
        camera_txt = "Enter a name for the camera: "
        site_txt = "Enter the site name: "
        folder_txt = "Enter the folder name for pictures: "
        nbrs_txt = "Select the number of snapshots to be taken: "
        username_txt = "Username: "
        password_txt = "Password: "
        ipaddr_txt = "IP Address: "
        httpport_txt = "Port: "

    name = "TakeSnapShots"
    description = "Takes a preconfigured number of snapshots from a camera."
    iconFile = "camera"

    def __call__(
        self,
        cameraname,
        sitename,
        folder_for_images,
        nbr_of_images,
        username,
        password,
        ipaddr,
        httpport
    ):
        self.sitename = sitename
        self.cameraname = cameraname
        self.folder_for_images = folder_for_images
        self.nbr_of_images = nbr_of_images
        self.username = username
        self.password = password
        self.ipaddr = ipaddr
        self.httpport = httpport
        today = datetime.now()
        path = today.strftime("%y%b%d")
        self.picture_path = folder_for_images + "\\" + sitename + "\\" + path
        print self.picture_path
        
        self.finished = Event()
        self.TakeSnapShot = Thread(
            target=self.TakeSnapShotThread,
            name="TakeSnapShots"
        )
        self.now = datetime.now()
        self.TakeSnapShot.start()


    def TakeSnapShotThread(self):
        while not self.finished.isSet():
            print "Capturing "+str(self.nbr_of_images)+" images..."
            camurl = "http://"+str(self.ipaddr)+":"+str(self.httpport)+"/snapshot.cgi?user="+str(self.username)+"&pwd="+str(self.password)
            for item in range(self.nbr_of_images):
                image1 = urllib2.urlopen(camurl)
                increment = str(item)
                filename = (
                    self.now.strftime("%y%b%d_%H-%M-%S.%f") +
                    "_" +
                    self.sitename +
                    "_" +
                    self.cameraname +
                    "-" +
                    increment +
                    ".jpg"
                )
                if(
                    not os.path.exists(self.picture_path)
                    and
                    not os.path.isdir(self.picture_path)
                ):
                    os.makedirs(self.picture_path)
                output1 = open(self.picture_path + "\\" + filename,'wb')
                output1.write(image1.read())
                output1.close()
                #self.finished.wait(0.1)
            print "Captured!"
            self.finished.set()
            time.sleep(0.1)
            print "Snap Shot action finished"


    def Configure(
        self,
        cameraname = 'camera name',
        sitename = 'sitename',
        folder_for_images = 'C:\CameraSnapshots\MyCams',
        nbr_of_images = 50,
        username = 'admin',
        password = '',
        ipaddr = 'XXX.XXX.XXX.XXX',
        httpport = 80
    ):
        text = self.text
        panel = eg.ConfigPanel()

        cameranameCtrl = wx.TextCtrl(panel, -1, cameraname)
        sitenameCtrl = wx.TextCtrl(panel, -1, sitename)
        folder_for_imagesCtrl = wx.TextCtrl(panel, -1, folder_for_images)
        snapShotCtrl = panel.SpinIntCtrl(nbr_of_images)
        usernameCtrl = wx.TextCtrl(panel, -1, username)
        passwordCtrl = wx.TextCtrl(panel, -1, password)
        ipaddrCtrl = wx.TextCtrl(panel, -1, ipaddr)
        httpportCtrl = panel.SpinIntCtrl(httpport)
        
        panel.AddLine(text.camera_txt, cameranameCtrl)
        panel.AddLine(text.site_txt, sitenameCtrl)
        panel.AddLine(text.folder_txt, folder_for_imagesCtrl)
        panel.AddLine(text.nbrs_txt, snapShotCtrl)
	panel.AddLine(text.username_txt, usernameCtrl)
	panel.AddLine(text.password_txt, passwordCtrl)
	panel.AddLine(text.ipaddr_txt, ipaddrCtrl)
	panel.AddLine(text.httpport_txt, httpportCtrl)
		
	
        while panel.Affirmed():
            panel.SetResult(
                cameranameCtrl.GetValue(),
                sitenameCtrl.GetValue(),
                folder_for_imagesCtrl.GetValue(),
                snapShotCtrl.GetValue(),
                usernameCtrl.GetValue(),
                passwordCtrl.GetValue(),
                ipaddrCtrl.GetValue(),
                httpportCtrl.GetValue()
            )
